<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2023/11/13
 * Time: 10:42 AM
 */

namespace App\Models\CacheModel\zl6;

use app\common\lib\Aes;
use App\Models\Api\BaseCache;
use think\Log;
use AstroTool\Cache\CacheManage;

class Zl6MeditationSection extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl6_meditation_section';

    protected $cacheModel = 'meditation.section';

    /**
     * 获取 冥想课程 章节列表ID
     * @return array
     * @throws \Exception
     */
    public function getDataSidsByMid(int $mid)
    {
        $ids = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $mid)->setSort('desc')->ZsGetIocData('list', function () use ($mid)
        {
            $data = $this->where(['cid' => $mid, 'status' => 1])->order("sort desc,id desc")->column('sort', 'id');
            $resIds = [];
            foreach ($data as $id => $sort)
            {
                $resIds[$id] = sprintf('%.6f', $sort + $id / 1000000);
            }
            return $resIds;
        }, true);

        return $ids;
    }

    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            return $this->where(['id' => ['in', $ids]])->column('*', 'id');
        }
        catch (\Exception $e)
        {
            Log::write('Zl6MeditationSection model => ()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return [];
        }
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'cid', 'sign_id', 'status', 'sort', 'is_audition', 'video_duration', 'create_time', 'update_time']);
        }

        return $data;
    }

    /**
     * @param int $mid
     * @param int $mType 1=>普通课程 2=>十二星座课程
     * @param int $uid
     * @param bool $isVipUnlock 是否VIP已解锁 【支持VIP免费 且 当前用户是VIP】
     * @param array $subInfo 订阅信息
     * @param bool $isVipFree 是否支持 VIP免费
     * @return array
     * @throws \Exception
     */
    public function getMeditionSectionListData(int $mid, int $mType, int $uid, bool $isVipUnlock, array $subInfo, bool $isVipFree)
    {
        $sids = $this->getDataSidsByMid($mid);
        $dataList = $this->batchGetInfoByIds(array_keys($sids));
        // 通过VIP已解锁 时 不获取 购买信息
        $meditationUnlockData = $isVipUnlock ? [] : (new Zl6MeditationUnlockData())->getUnlockDatas($uid);
        $playData = $uid === 0 ? [] : (new Zl6MeditationPlayRecord())->getMeditionSectionPlayRecordPageDataIds($uid, $mid); //
        if ($mType === 1)
        {
            $sectionDataList = [
                0 => [
                    'status' => 1,  // 默认已解锁
                    'list' => []
                ]
            ];
        } else
        {
            $sectionDataList = [
                1 => ['status' => 1, 'list' => []], 2 => ['status' => 1, 'list' => []], 3 => ['status' => 1, 'list' => []], 4 => ['status' => 1, 'list' => []],
                5 => ['status' => 1, 'list' => []], 6 => ['status' => 1, 'list' => []], 7 => ['status' => 1, 'list' => []], 8 => ['status' => 1, 'list' => []],
                9 => ['status' => 1, 'list' => []], 10 => ['status' => 1, 'list' => []], 11 => ['status' => 1, 'list' => []], 12 => ['status' => 1, 'list' => []]
            ];
        }
        foreach ($sids as $sid => $sort)
        {
            $item = $dataList[$sid];
            $item['sign_id'] = $mType === 2 ? $item['sign_id'] : 0;
            if ($mType === 2 && !isset($sectionDataList[$item['sign_id']]))
            {
                continue;
            }
            if ($item['is_audition'] === 1 || $isVipUnlock || in_array($mid . ':' . $item['sign_id'], $meditationUnlockData, true))
            {   // 试听 | 是VIP ｜ 已购买
                $status = 1;    // 1=>可播放 0=>未解锁
            } else
            {   // 不可播放
                $status = 0;    // 1=>可播放 0=>未解锁
            }
            $resItem = [
                'id' => $item['id'],
                'title' => $item['title'],
                'tip' => isset($playData[$sid]) ? '听过' : '',
                'duration' => $item['video_duration'],
                'status' => $status,
            ];
            if ($status === 0)
            {   // 未解锁 有不能播放的 章节 说明未解锁
                $sectionDataList[$item['sign_id']]['status'] = 0;
            }
            $sectionDataList[$item['sign_id']]['list'][] = $resItem;
        }

        $inSignNames = [
            1 => '白羊座',
            2 => '金牛座',
            3 => '双子座',
            4 => '巨蟹座',
            5 => '狮子座',
            6 => '处女座',
            7 => '天秤座',
            8 => '天蝎座',
            9 => '射手座',
            10 => '摩羯座',
            11 => '水瓶座',
            12 => '双鱼座',
        ];
        $resDataList = [];
        foreach ($sectionDataList as $signId => $sectionData)
        {
            $btnData = [];
            if ($uid === 0)
            {
                $btnData = [
                    [
                        'name' => '登录解锁更多精彩',
                        'type' => 0,
                        'bg_color' => '#4C60D6',
                    ]
                ];
                $unlockToastType = 1;
            } else
            {
                if ($sectionData['status'] === 0)
                {   // 未解锁
                    $unlockToastType = 2;
                    if ($signId === 0)
                    {   // 普通冥想课程 信息
                        $btnData = [
                            [
                                'name' => '购买',
                                'type' => 1,
                                'bg_color' => '#4C60D6',
                            ]
                        ];
                    } else
                    {   // 12星座信息
                        $btnData = [
                            [
                                'name' => '解锁' . $inSignNames[$signId],
                                'type' => 1,
                                'bg_color' => '#4C60D6',
                            ]
                        ];
                    }

                    if ($isVipFree)
                    {   // 支持 VIP免费解锁
                        $unlockToastType = 3;
                        $btnData[] = [
                            'name' => '小行星会员免费解锁',
                            'type' => 2,
                            'bg_color' => '#FEB04E',
                        ];
                    }
                }
            }

            $resDataList[] = [
                'sign' => $signId,
                'list' => $sectionData['list'],
                'btn_data' => $btnData,
                'status' => $sectionData['status'],
                'unlock_toast_type' => $unlockToastType ?? 0,
                'sub_info' => $subInfo ?: null,
            ];
        }

        return $resDataList;
    }

    /**
     * 获取 已解锁可播放 章节列表
     * @param int $mid
     * @param int $mType 1=>普通课程 2=>十二星座课程
     * @param int $uid
     * @param int $signId // 星座ID 1-12  普通课程为0
     * @param bool $isVipUnlock 是否VIP已解锁 【支持VIP免费 且 当前用户是VIP】
     * @return array
     * @throws \Exception
     */
    public function getSectionPlayUnlockListData(int $mid, int $mType, int $uid, int $signId, bool $isVipUnlock)
    {
        $sids = $this->getDataSidsByMid($mid);
        $dataList = $this->batchGetInfoByIds(array_keys($sids));
        // 通过VIP已解锁 时 不获取 购买信息
        $isUnlock = $isVipUnlock || (new Zl6MeditationUnlockData())->isUnlock($uid, $mid, $signId);

        $sectionDataList = [
            'status' => $isUnlock ? 1 : 0,  // 1 已解锁 2=>未解锁
            'list' => []
        ];
        $aesModel = new Aes();
        foreach ($sids as $sid => $sort)
        {
            $item = $dataList[$sid];
            $item['sign_id'] = $mType === 2 ? $item['sign_id'] : 0;
            if ($item['sign_id'] !== $signId)
            {   // 非当前 星座
                continue;
            }
            if ($item['is_audition'] === 1 || $isUnlock)
            {   // 试听 | 是VIP ｜ 已购买
                $status = 1;    // 1=>可播放 0=>未解锁
            } else
            {   // 不可播放
                $status = 0;    // 1=>可播放 0=>未解锁
            }
            if ($status === 0)
            {   // 未解锁 有不能播放的 跳过
                continue;
            }
            $resItem = [
                'id' => $item['id'],
                'title' => $item['title'],
                'duration' => $item['video_duration'],
                'audio' => $aesModel->encryptWithOpenssl($item['vid']),
            ];

            $sectionDataList['list'][] = $resItem;
        }

        return $sectionDataList;
    }
}
